package com.ess.project.examine.record.service;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ess.common.utils.text.Convert;
import com.ess.project.examine.grade.domain.ExamineGradeEntity;
import com.ess.project.examine.grade.mapper.ExamineGradeMapper;
import com.ess.project.examine.grade.service.IGradeService;
import com.ess.project.examine.record.compute.*;
import com.ess.project.examine.record.listener.ExamineRecordEntityListener;
import com.ess.project.examine.record.util.ExcelUtil;
import com.ess.project.examine.record.domain.ExamineRecordEntity;
import com.ess.project.examine.record.mapper.RecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @Description:
 * @Date: Created in 11:34 上午 2021/3/17
 * @Author: daihui
 * @Modified By:
 */
@Slf4j
@Service("recordService")
public class RecordServiceImpl extends ServiceImpl<RecordMapper, ExamineRecordEntity> implements IRecordService {


    @Autowired
    private RecordMapper recordMapper;

    @Override
    public List<ExamineRecordEntity> selectRecordList(ExamineRecordEntity record) {
        QueryWrapper<ExamineRecordEntity> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(record.getPersonnelCategory())) {
            wrapper.eq("personnel_category", record.getPersonnelCategory());
        }
        if (StrUtil.isNotEmpty(record.getExamPersonnel())) {
            wrapper.like("exam_personnel", record.getExamPersonnel());
        }
        if (StrUtil.isNotEmpty(record.getExamTime())) {
            wrapper.eq("exam_time", record.getExamTime());
        }
        return recordMapper.selectList(wrapper);
    }

    @Override
    public List<ExamineGradeEntity> importRecordData(InputStream inputStream) {
        List<ExamineGradeEntity> exportData = new ArrayList<>();
        List<ExamineRecordEntity> importData = EasyExcel.read(inputStream, ExamineRecordEntity.class, new ExamineRecordEntityListener(this)).sheet().headRowNumber(3).doReadSync();
        String personnelCategory = importData.get(0).getPersonnelCategory();
        String examTime =  importData.get(0).getExamTime();
        for (ExamineRecordEntity importInfo : importData) {
            String name = importInfo.getExamPersonnel();
            Integer age = importInfo.getAge();
            String gender = importInfo.getGender();
            Float height = importInfo.getHeight();
            Float weight = importInfo.getWeight();
            Float bodyFat = importInfo.getBodyFat();
            Integer minute = importInfo.getThreeKmMinute();
            Integer second = importInfo.getThreeKmSecond();
            Integer examScore = importInfo.getExamScore();
            Integer sitUp = importInfo.getSitUp();
            Float snakeRun = importInfo.getSnakeRun();

            ExamineGradeEntity.ExamineGradeEntityBuilder exportInfoBuilder = ExamineGradeEntity.builder();

            if (ObjectUtil.isAllEmpty(height, weight, minute, second, examScore, sitUp, snakeRun)) {
                exportInfoBuilder.examPersonnel(name).age(age).gender(gender).totalScore("缺考").gradeEvaluation("缺考").personnelCategory(personnelCategory).examTime(examTime);
                exportData.add(exportInfoBuilder.build());
            } else {
                ExamineContext<Float> bodilyFormExamine = new ExamineContext<>(new BodilyFormExamineStrategy());
                ExamineContext<Integer> threeKmExamine = new ExamineContext<>(new ThreeKmExamineStrategy());
                ExamineContext<Integer> threeTermExamine = new ExamineContext<>(new ThreeTermExamineStrategy());
                ExamineContext<Integer> situpExamine = new ExamineContext<>(new SitupExamineStrategy());
                ExamineContext<Float> snakeRunExamine;
                snakeRunExamine = new ExamineContext<>(new SnakeRunExamineStrategy());
                ExamineContext<Integer> evaluateExamine = new ExamineContext<>(new EvaluateExamineStrategy());

                String bodilyFormScore = (String) bodilyFormExamine.executeStrategy(age, gender, height, weight, bodyFat);
                Integer threeKmScore = (Integer) threeKmExamine.executeStrategy(age, gender, minute, second);
                Integer threeExamScore = (Integer) threeTermExamine.executeStrategy(age, gender, examScore);
                Integer situpScore = (Integer) situpExamine.executeStrategy(age, gender, sitUp);
                Integer snakeRunScore = (Integer) snakeRunExamine.executeStrategy(age, gender, snakeRun);
                // 总分
                Integer totalScore = threeKmScore + threeExamScore + situpScore + snakeRunScore;
                // 划分等级
                String evaluate = (String) evaluateExamine.executeStrategy(personnelCategory, bodilyFormScore, threeKmScore, threeExamScore, situpScore, snakeRunScore, totalScore);
                ExamineGradeEntity exportExamInfoEntity = exportInfoBuilder.examPersonnel(name).age(age).gender(gender).bodilyForm(bodilyFormScore)
                        .threeKmScore(threeKmScore).horizontalbarPushupScore(threeExamScore).situpScore(situpScore)
                        .snakeRunScore(snakeRunScore).totalScore(totalScore).gradeEvaluation(evaluate).personnelCategory(personnelCategory).examTime(examTime).build();
                exportData.add(exportExamInfoEntity);
            }
        }
        return exportData;
    }

    @Override
    public List<ExamineRecordEntity> selectExamineTimeList() {
        return recordMapper.selectExamineTimeList();
    }

    @Override
    public ExamineRecordEntity selectRecordById(Integer recordId) {
        return recordMapper.selectById(recordId);
    }

    @Override
    public int updateRecord(ExamineRecordEntity record) {
        return recordMapper.updateById(record);
    }

    @Override
    public int deleteRecordByIds(String ids) {
        Long[] recordIds = Convert.toLongArray(ids);
        return recordMapper.deleteRecordByIds(recordIds);
    }

    @Override
    public void export(ExamineRecordEntity record, HttpServletResponse response) {
        QueryWrapper<ExamineRecordEntity> wrapper = new QueryWrapper<>();
        String personnelCategory = record.getPersonnelCategory();
        if (StrUtil.isNotEmpty(personnelCategory)) {
            wrapper.eq("personnel_category", record.getPersonnelCategory());
            wrapper.eq("attend", "1");
        }
        List<ExamineRecordEntity> data = recordMapper.selectList(wrapper);

        Stream.iterate(0, i -> i + 1).limit(data.size()).forEach(index -> data.get(index).setSerialNumber(index + 1));
        String examTime = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月"));
        Map<String, Object> header = new HashMap<>(2);
        header.put("personnelCategory", personnelCategory);
        header.put("examTime", examTime);
        try {
            String exportName = examTime + "_" + personnelCategory + "_体能训练输入表";
            String template = "template/importTemplate.xlsx";
            ExcelUtil.writeExcelByTemplate(response, template, data, exportName, header, ExamineRecordEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据异常");
        }
    }


}
